package com.example.androiddemo;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView mBottomNavigationView;
    private FrameLayout mContainer ;
    private ArrayList<Fragment>  mFragments = new ArrayList<>();
    private int mLastPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
    }

    private void initView(){
        mBottomNavigationView = findViewById(R.id.activity_main_bottom);
        mContainer = findViewById(R.id.activity_main_container);

        mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId();
                switch (itemId) {
                    case R.id.menu_push:
                        setFragmentPosition(0);
                        break;
                    case R.id.menu_get:
                        setFragmentPosition(1);
                        break;
                    case R.id.menu_video:
                        setFragmentPosition(2);
                        break;
                }
                return true;
            }
        });
    }

    private void initData(){
        mFragments.add(new PushItemFragment());
        mFragments.add(new GetItemFragment());
        mFragments.add(new VideoItemFragment());
        setFragmentPosition(0);
    }

    private void setFragmentPosition(int position){
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment currFragment = mFragments.get(position);
        Fragment lastFragment = mFragments.get(mLastPosition);
        mLastPosition = position;
        ft.hide(lastFragment);
        if( !currFragment.isAdded() ){
            FragmentTransaction f = getSupportFragmentManager().beginTransaction();
            f.remove(currFragment).commit();
            ft.add(R.id.activity_main_container, currFragment);
        }
        ft.show(currFragment);
        ft.commitAllowingStateLoss();
    }
}